import pyaudio
import wave
import requests
import time
import base64
import pyperclip

def wav_to_base64(filename):
    with open(filename, 'r', encoding='ISO-8859-1') as wav_file:
        wav_data = wav_file.read()
    # 将 WAV 数据进行 Base64 编码，并移除回车换行符
    encoded_wav = base64.b64encode(wav_data.encode('utf-8')).decode('utf-8').replace('\n', '')
    return encoded_wav

def asr():
    """ 使用Tencentcloude转换成文字 """
    url = 'https://asr.tencentcloudapi.com'
    timestamp = str(int(time.time()))
    print(timestamp)
    bs64 = wav_to_base64(outwav)
    # print(bs64)

    json = {
        "UsrAudioKey": "test",
        "SubServiceType": 2,
        "ProjectId": 0,
        "EngSerViceType": "8k_zh",
        "VoiceFormat": "wav",
        "Data": bs64,
        "SourceType": 1
    }
    headers= {
        # 'Content-Type': 'application/json; charset=utf-8',
        # 'X-TC-Version': '2019-08-23',
        'X-TC-Version': '2019-06-14',
        'X-TC-Region': 'ap-guangzhou',
        'X-TC-Action': 'SentenceRecognition',
        'X-TC-Timestamp': timestamp,
        'Authorization':'',
        'Host': url[8:],

    }
    r = requests.post(url=url, json=json, headers=headers)
    print(r.status_code)
    print(r.request.headers)
    print(r.content)
    pyperclip.copy(r.content.decode('utf-8'))


# record_audio(outwav, 10)
# asr()
